package dao;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import util.PZUtil;

public class BasicDao<T> {
	private Class<T> baclass;
	@SuppressWarnings("unchecked")
	public BasicDao() {
		ParameterizedType pt=(ParameterizedType) this.getClass().getGenericSuperclass();
		baclass=(Class<T>) pt.getActualTypeArguments()[0];
	}
	
	public List<T> getAll(){
		List<T> list=new ArrayList<>();
		StringBuffer sql=new StringBuffer("select * from ")
					.append(baclass.getSimpleName());
		Field[] field=baclass.getDeclaredFields();
		Connection con=PZUtil.getConnection();
		try {
			PreparedStatement pst=con.prepareStatement(sql.toString());
			ResultSet rs=pst.executeQuery();
			while(rs.next()){
				T o=baclass.newInstance();
				for(int i=0;i<field.length;i++){
					field[i].setAccessible(true);
					field[i].set(o, rs.getObject(i+1));
				}
				list.add(o);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		return list;
		
	}
}
